<template>
    <a-modal :visible="state.visible" title="Basic Modal"   wrap-class-name="full-modal" width="100%" @cancel="handleCancel" @ok="handleOk">
        <AForm class="plan-scheme-modal" ref="formRef" :model="state.formData"  :labelCol="{style:'width:80px'}">
            <!-- <AFormItem label="选择企划" name="planId">
                <ASelect v-model:value="state.formData.planId">
                    <ASelectOption :value="1">春夏季文化节</ASelectOption>
                </ASelect>
            </AFormItem> -->
            <AFormItem label="方案名称" name="title" :rules="[{required:true,message:'请填写'}]">
                <AInput class="width-600" v-model:value="state.formData.title" :maxlength="50"></AInput>
            </AFormItem>
            <AFormItem label="参与人群" name="crowdRange" :rules="[{required:true,message:'请选择'}]">
                <a-radio-group v-model:value="state.formData.crowdRange" name="scope">
                    <a-radio :value="1">所有人</a-radio>
                    <a-radio :value="2">新人</a-radio>
                    <a-radio :value="3">会员</a-radio>
                </a-radio-group>
            </AFormItem>
            <AFormItem label="促销对象" name="scope" :rules="[{required:true,message:'请选择'}]">
                <a-radio-group v-model:value="state.formData.scope" name="scope" @change="handelScopeChange">
                    <a-radio :value="scopeEnum.WholeOrder">整单</a-radio>
                    <a-radio :value="scopeEnum.Category">品类</a-radio>
                    <a-radio disabled :value="scopeEnum.Packages" title="暂不支持">套餐</a-radio>
                    <a-radio :value="scopeEnum.Single">单品</a-radio>
                </a-radio-group>
            </AFormItem>
            <AFormItem label="选择促销类型" name="crowdRange" :rules="[{required:true,message:'请选择'}]">
                <ASelect class="width-600" v-model:value="state.formData.promoTypeId" :options="promoTypeOptions">
                </ASelect>
            </AFormItem>
            <a-divider dashed />
            <AFormItem label="设置档位" name="schemeStairs" :rules="[{required:true,message:'请选择'}]">
            <div v-for="(stair,stairIndex) in state.formData.schemeStairs" class="scheme-stairs">
                <div class="scheme-stairs-label">第{{stairIndex+1}}档</div>
                <div class="scheme-stairs-content"> 
                    <div style="display: flex;align-items: center;">
                        <AFormItem :name="['schemeStairs',stairIndex,'thresholdNum']" :rules="[{required:true,message:'请填写'}]">
                            <div class="flex-row">
                                满<a-input class="width-100" v-model:value="stair.thresholdNum"></a-input>{{thresholdUnit(stair)}}
                            </div>
                        </AFormItem>
                    </div>
                    <div v-for="(gear,gearIndex) in stair.gears">
                              <div v-if="gear.type === preferentialEnum.Subtraction" class="flex-row">
                                <span>减</span>
                                <AFormItem :name="['schemeStairs',stairIndex,'gears',gearIndex,'value']"  :rules="[{required:true,message:'请填写'}]">
                                    <a-input class="width-100 stairs-input" v-model:value="gear.value" suffix="元"></a-input>
                                </AFormItem>
                              </div>
                              <div v-if="gear.type === preferentialEnum.Discount" class="flex-row">
                                <span>打</span>
                                <AFormItem  :name="['schemeStairs',stairIndex,'gears',gearIndex,'value']" :rules="[{required:true,message:'请填写'}]">
                                    <a-input class="width-100  stairs-input" v-model:value="gear.value" suffix="折"></a-input>
                                </AFormItem>
                              </div>
                              <div v-if="gear.type === preferentialEnum.Special" class="flex-row">
                                <span>特价</span>
                                <AFormItem  :name="['schemeStairs',stairIndex,'gears',gearIndex,'value']" :rules="[{required:true,message:'请填写'}]">
                                    <a-input class="width-100  stairs-input" v-model:value="gear.value" suffix="元"></a-input>
                                </AFormItem>
                            </div>
                            <div v-if="gear.type === preferentialEnum.Gift" class="flex-row">
                                <span>赠</span>
                                <AFormItem v-if="gear.objType === objTypeEnum.Self" 
                                 :name="['schemeStairs',stairIndex,'gears',gearIndex,'value']"
                                  :rules="[{required:true,message:'请填写'}]">
                                    <a-input class="width-100  stairs-input" v-model:value="gear.value" suffix="件"></a-input>
                                    本品
                                </AFormItem>
                                <AFormItem v-if="gear.objType === objTypeEnum.Coupon" 
                                :name="['schemeStairs',stairIndex,'gears',gearIndex,'descrValue']"
                                :rules="[{required:true,message:'请填写'}]">
                                    优惠券：<a-input class="width-100  stairs-input" 
                                    v-model:value="gear.descrValue"
                                     @keyup.enter="(event)=>findCoupon(event,gear)" 
                                     @blur="(event)=>findCoupon(event,gear)"></a-input>
                                    {{ gear.descr }}
                                </AFormItem>
                                
                                <AFormItem v-if="gear.objType === objTypeEnum.Gift"
                                :name="['schemeStairs',stairIndex,'gears',gearIndex,'gifts']"
                                 :rules="[{required:true,message:'请选择',trigger:'change'}]">
                                    以下<GiftsSelect v-model:value="gear.gifts"></GiftsSelect>商品
                                </AFormItem>
                            </div>               
                    </div>
                    <div  class="flex-row">
                        <a-button @click="removeStairsIndex(stairIndex)" type="text">删除</a-button>
                    </div>    
                </div>
            </div>
            <a-button type="primary" @click="addGear">添加挡位</a-button>
        </AFormItem>
        <a-divider dashed />
        <AFormItem v-if="state.formData.scope===scopeEnum.Category" 
        label="参与品类"
        name="categories"
        :rules="[{required:true,message:'请选择',trigger:'change'}]"
        >
            <a-select v-model:value="state.formData.categories" allowClear mode="multiple">
              <a-select-option v-for="(categoryItem,categoryItemIndex) in state.goodsCategoryOptions" 
              :key="categoryItemIndex" 
              :value="categoryItem.goodsCategoryId">
                {{ categoryItem.goodsCategoryName}}
            </a-select-option>
            </a-select>
        </AFormItem>
        <AFormItem v-if="state.formData.scope===scopeEnum.Single"
         label="参与商品"
         name="goods"
        :rules="[{required:true,message:'请选择'}]">
            <div class="mb-10">
                <a-button type="primary" @click="addFormGoods">添加参与商品</a-button>
            </div>
            <a-table :data-source="state.formData.goods" :pagination="false">
                <a-table-column key="goodsCode" data-index="goodsCode"  title="商品编码">
                    <template #default="{record}">{{ record.goodsCode }}</template>
                </a-table-column>
                <a-table-column key="goodsName" data-index="goodsName"  title="商品名称">
                    <template #default="{record}">{{ record.goodsName }}</template>
                </a-table-column>
                <a-table-column key="originalPrice" data-index="originalPrice"  title="原始价格">
                    <template #default="{record}">{{ record.originalPrice }}</template>
                </a-table-column>
                <a-table-column key="salePrice" data-index="salePrice"  title="销售价格">
                    <template #default="{record}">{{ record.salePrice }}</template>
                </a-table-column>
                <a-table-column key="salePrice" data-index="salePrice"  title="操作">
                    <template #default="{record,index}">
                        <a-button @click="removeGoodsItem(record,index)">移除</a-button>
                    </template>
                </a-table-column>
            </a-table>
        </AFormItem>    
        </AForm>
        <GoodsModal  
        v-if="state.goodsModalVisible"
        @ok="receiveGoods" 
        @cancel="state.goodsModalVisible = false"></GoodsModal>
    </a-modal>
    </template>
    <script lang="ts" setup>
    import {GoodsCategoryTypes, GoodsTypes, PromoTypes, ResponseVo, UserTypes, objTypeEnum, preferentialEnum, scopeEnum, thresholdEnum} from "@/type";
    import { reactive,ref,onMounted,computed } from "vue";
    import { PlanSchemeTypes } from "@/type/planScheme";
    import { CouponService, GoodsCategoryService, PlanSchemeService, PromoService } from "@/service";
    import { GoodsModal,GiftsSelect } from "@/components/index"
import { message } from "ant-design-vue";
   
    const props = withDefaults(defineProps<{
        currentScheme?:Partial<PlanSchemeTypes.planSchemeItem>;
    }>(),{
        currentScheme:():Partial<PlanSchemeTypes.planSchemeItem>=>({})
    })
    
    const formRef = ref()
    const emit = defineEmits<{
        (e:"ok"):void,
        (e:"cancel"):void
    }>()
    
    const state = reactive<{
        formData:Partial<PlanSchemeTypes.planSchemeItem>;
        visible: boolean,
        promoList:PromoTypes.IPromoItem[],
        goodsModalVisible: boolean,
        goodsCategoryOptions:GoodsCategoryTypes.GoodsCategoryItem[]
    }>({
        formData:{},
        visible: true,
        promoList:[],
        goodsModalVisible: false,
        goodsCategoryOptions:[]
    })
    
    onMounted(()=>{
        getListPromo();
        getGoodsCategory();
        state.formData = {...props.currentScheme};
    })

    const promoTypeOptions = computed(()=>{
        return state.promoList.filter((promoType:PromoTypes.IPromoItem)=>{
            return promoType.scope === state.formData.scope;
        }).map((promoType:PromoTypes.IPromoItem)=>{
            return {
                value:promoType.id,
                label:promoType.title
            }
        })
    })

    const activePromo = computed(()=>{
        return state.promoList.find((promoType:PromoTypes.IPromoItem)=>promoType.id === state.formData.promoTypeId);
    }) 

    const getGoodsCategory = async()=>{
    const res:ResponseVo<GoodsCategoryTypes.GoodsCategoryItem[]>= await GoodsCategoryService.findAllGoodsCategory();
    if(res.code===0){
        state.goodsCategoryOptions = res.data;
    }
}

    const getListPromo = async()=>{
      let res = await PromoService.listPromo();
      if(res.code===0){
        state.promoList = res.data;
      }
    }

    const handelScopeChange = ()=>{
        state.formData.promoTypeId = undefined;
         //重置方案商品
         state.formData.goods = []
        //重置档位数据
        state.formData.schemeStairs = [];
        //重置促销类型
        state.formData.promoTypeId = undefined;
    }

    const removeStairsIndex = (stairsIndex:number)=>{
        state.formData.schemeStairs?.splice(stairsIndex,1)
    }

    const  thresholdUnit= (stair:Partial<PlanSchemeTypes.ISchemeStairs>)=>{
        console.log("stair--->",stair)
        if(stair.threshold===thresholdEnum.Quantity)return"件";
        if(stair.threshold===thresholdEnum.Amount)return"元";
    }

    const addGear = ()=>{
        if(!state.formData.promoTypeId)return message.error("请先选择促销类型");
        if(state.formData.schemeStairs===undefined)state.formData.schemeStairs=[]
        state.formData.schemeStairs.push({
            threshold:activePromo.value?.threshold,
            gears:activePromo.value?.promoGears.map((promoGear)=>{
                return {
                    dataType: promoGear.dataType,
                    type:  promoGear.type,
                    objType: promoGear.objType,
                    descr: promoGear.descr,
                    descrValue: promoGear.descr
                }
            })
        })
        console.log("state.formData.schemeGears---->",state.formData.schemeStairs)
    }

    const addFormGoods = ()=>{
        state.goodsModalVisible = true;
    }

    const removeGoodsItem = (record:Partial<GoodsTypes.IGoodsItem>,index:number)=>{
        state.formData.goods?.splice(index,1);
    }

    const receiveGoods = (values:any)=>{
        // values = values.map((value:GoodsTypes.IGoodsItem)=>{
        //     value.type = 1;
        //     return value;
        // })
        state.goodsModalVisible = false;
        if(state.formData.goods===undefined)state.formData.goods=[];
        state.formData.goods.push(...values);
        console.log("state.formData.goods--->",state.formData.goods)
    }

    const findCoupon = async(event:any,gear:Partial<PlanSchemeTypes.ISchemeGears>)=>{
        let val = event.target.value;
        if(val==="")return;
        const res = await CouponService.detailCoupon(val);
        if(res.code===0){
            gear.descrValue = String(res.data.id);
            gear.descr = res.data.title;
            console.log("gear--->",gear)
        }
    }
    
    const handleOk = async()=>{
        formRef.value.validateFields().then(async(valid:boolean)=>{
            if(valid){
                console.log("state.formData--->",state.formData);
                let sendData:any = JSON.parse(JSON.stringify(state.formData));
                if(state.formData.scope===scopeEnum.Category){
                    sendData.categories = sendData.categories.map((categoryId: number)=>({categoryId}))
                }
               
                let res:ResponseVo<any>
                if(state.formData.id){
                    res = await PlanSchemeService.editPlanScheme(sendData);
                }else{
                     res = await PlanSchemeService.addPlanScheme(sendData); 
                }  
                if(res.code===0){
                        emit("ok");
                    }
               
            }
        })
    }
    
    const handleCancel = ()=>{
        emit("cancel")
    }
    </script>
<style lang="less" scoped>

.scheme-stairs{
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
    align-items: center;
    :deep(.ant-form-item){
        margin-bottom: 0;
       
    }
    :deep(.ant-form-item-explain){
            position: absolute;
            width: 100%;
            left: 18px;
            bottom: -24px;
            
        }
    .stairs-input{
        margin-left:4px;
        margin-right: 4px;
    }
    .scheme-stairs-content{
        display: flex;
        gap:8px;
    }
    .scheme-stairs-label{
        color: #888888;
        margin-right: 8px;
    }
}
</style>